package com.gaga.common.utils;

import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @DESCRIPTION:
 * @USER: ningxiang
 * @DATE: 4/21/2025 4:19 PM
 */
@Slf4j
public class FolderSelector {
    // 关键点2：静态初始化FX环境（仅一次）
    static {
        new JFXPanel(); // 初始化JavaFX Toolkit
    }

    public String selectFolder() {
        AtomicReference<String> selectedPath = new AtomicReference<>();
        CountDownLatch latch = new CountDownLatch(1); // 关键点3：同步等待用户选择

        // 关键点4：确保在FX线程操作
        Platform.runLater(() -> {
            DirectoryChooser chooser = new DirectoryChooser();
            chooser.setTitle("选择文件夹");
            File dir = chooser.showDialog(new Stage()); // 使用新Stage

            if (dir != null) {
                selectedPath.set(dir.getAbsolutePath());
                log.info("选中路径: {}", dir.getAbsolutePath());
            }
            latch.countDown(); // 释放锁
        });

        try {
            latch.await(); // 等待用户选择完成
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return selectedPath.get();
    }
}